# forms.py
import re
from datetime import datetime

from django import forms
from .models import Member


class MemberForm(forms.ModelForm):
    class Meta:
        model = Member
        fields = ('Mname', 'Msex', 'Mcard', 'Mtel', 'other')

    def save(self, commit=True):
        member = super().save(commit=False)
        data = self.cleaned_data['Mcard']

        if data:
            match = re.search(r'\d{6}(\d{8})\d{4}', data)
            if match:
                try:
                    birthday = match.group(1)
                    birthday_date = datetime.strptime(birthday, '%Y%m%d').date()
                    member.Mbirthday = birthday_date.strftime('%Y-%m-%d')
                except ValueError:
                    raise forms.ValidationError('身份证号格式不正确，无法解析生日。')
            else:
                raise forms.ValidationError('身份证号格式不正确，无法解析生日。')

        if commit:
            member.save()

        return member